package com.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.project.bean.UserBean;
import com.project.bean.UserStatusEnum;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private com.project.webOneService.IUserService webUsersService;

    @RequestMapping("login")
    public Boolean login(String username, String password){
        UserBean userBean = userService.login(username, password);
        if (userBean != null) {
            return true;
        }
        return  false;
    }
    @RequestMapping("findAllUsers")
    public IPage<UserBean> findAllUsers(int pageNO){
        return userService.findAllUsers(pageNO);
    }

    @RequestMapping("updateUserStatus")
    public ResponseEntity<String> updateUserStatus(@RequestParam("userId") String userId,
                                                   @RequestParam("status") String status) {
        // 参数校验
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(status)) {
            return ResponseEntity.badRequest().body("userId or status is empty.");
        }

        int webUserStatus = 0;
        UserBean userBean;
        try {
            userBean = userService.updateUserStatus(userId, status);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update user status.");
        }

        if (userBean == null) {
            return ResponseEntity.notFound().build();
        }

        if (UserStatusEnum.FROZEN.getValue().equals(status)) {
            webUserStatus = 1;
        } else if (UserStatusEnum.UNFROZEN.getValue().equals(status)) {
            webUserStatus = 0;
        } else {
            return ResponseEntity.badRequest().body("Invalid user status.");
        }

        try {
            String result = webUsersService.updateCustomtStatus(webUserStatus, userId);
            return ResponseEntity.ok("ok");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update web user status.");
        }
    }

}
